package com.zxy.locationtest2;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class Main extends Activity
{

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		start();
	}

	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.main, menu);

		menu.add(0, 1, 1, "搜星");
		menu.add(0, 2, 2, "退出");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case 1:
				initLocation();
				break;
			case 2:
				exit();
				break;
		}

		// Toast t=Toast.makeText(this,"你选的是苹果",Toast.LENGTH_SHORT);
		// t.show();

		return true;
	}

	private Button btn1;
	private TextView tv1;
	private TextView tv2;
	private TextView tv3;
	private TextView tv4;
	private TextView tv5;
	private ListView lv1;

	private void start()
	{
		initView();
		initLocation();

	}

	/**
	 * 初始化view
	 */
	private void initView()
	{
		btn1 = (Button) findViewById(R.id.button1);
		tv1 = (TextView) findViewById(R.id.textView1);
		tv2 = (TextView) findViewById(R.id.textView2);
		tv3 = (TextView) findViewById(R.id.textView3);
		tv4 = (TextView) findViewById(R.id.textView4);
		tv5 = (TextView) findViewById(R.id.textView5);
		lv1 = (ListView) findViewById(R.id.listView1);
		btn1.setOnClickListener(onClick1);
	}

	/**
	 * 按钮点击事件
	 */
	private OnClickListener onClick1 = new OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			showLatlng();
			clearLv();
			showError("");
			sendPost();
		}

	};

	/**
	 * 向服务器发送数据
	 */
	private void sendPost()
	{
		double lat = loc.getLatitude();
		double lng = loc.getLongitude();
		// double lat=40.053228;
		// double lng=116.301377;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("lat", lat + ""));
		params.add(new BasicNameValuePair("lon", lng + ""));
		String result = Client.sendPost(Client.GET_LATLOG, params);
		updateLv(result);
	}

	/**
	 * 清除ListView数据
	 */
	private void clearLv()
	{
		ArrayList<Object> list = new ArrayList<Object>();
		lv1.setAdapter(new ArrayAdapter<Object>(this,
				android.R.layout.simple_expandable_list_item_1, list));
	}

	/**
	 * 更新ListView数据
	 * 
	 * @param result
	 */
	@SuppressWarnings(
	{ "unchecked", "rawtypes" })
	private void updateLv(String result)
	{
		

		List list = new ArrayList();
		JSONArray data;
		String error;

		try
		{
			data = new JSONObject(result).getJSONArray("data");
			for (int i = 0; i < data.length(); i++)
			{
				JSONObject item = (JSONObject) data.opt(i);
				list.add(item.getString("name"));
			}
			lv1.setAdapter(new ArrayAdapter(this,
					android.R.layout.simple_expandable_list_item_1, list));
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
		try
		{
			error = new JSONObject(result).getString("error");
			showError(error);
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	LocationManager lm;
	Location loc;
	String currentProvider;

	/**
	 * 初始化定位
	 */
	private void initLocation()
	{
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.addGpsStatusListener(listener);

		Criteria cri = new Criteria();
		cri.setAccuracy(Criteria.ACCURACY_COARSE);
		cri.setAltitudeRequired(true);
		cri.setBearingRequired(true);
		cri.setSpeedRequired(true);
		cri.setCostAllowed(true);
		cri.setPowerRequirement(Criteria.POWER_HIGH);

		currentProvider = lm.getBestProvider(cri, true);

		showTypeAndNum();

		loc = lm.getLastKnownLocation(currentProvider);
		lm.requestLocationUpdates(currentProvider, 0, 0, onLocationListener);

	}

	private int satellites = 0;
	/**
	 * 侦听GPS状态
	 */
	private Listener listener = new Listener()
	{

		@SuppressWarnings("unused")
		@Override
		public void onGpsStatusChanged(int event)
		{
			// TODOAuto-generated
			// method stub
			String code = "";
			switch (event)
			{
				case GpsStatus.GPS_EVENT_STARTED:
					code = "GPS系统模块被开启";
					break;
				case GpsStatus.GPS_EVENT_STOPPED:
					code = "GPS系统模块被关闭";
					break;
				case GpsStatus.GPS_EVENT_FIRST_FIX:
					code = "GPS系统模块接收到第一次GPS定位信息";
					break;
				case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
					code = "周期性发送GPS卫星状态";
					GpsStatus gpsStatus = lm.getGpsStatus(null);
					// 获取卫星最大值
					int maxSatellites = gpsStatus.getMaxSatellites();
					// 创建迭代器保存所有卫星
					Iterator<GpsSatellite> it = gpsStatus.getSatellites()
							.iterator();
					int count = 0;
					while (it.hasNext() && count <= maxSatellites)
					{
						GpsSatellite s = it.next();
						count++;
					}
					satellites = count;
					showTypeAndNum();
					break;
			}
			showGPSStatus(code);
		}

	};

	/**
	 * 侦听GPS数据
	 */
	private LocationListener onLocationListener = new LocationListener()
	{

		@Override
		public void onLocationChanged(Location location)
		{
			// Auto-generated method stub
			showLMStatus("位置发生变化"+"。  运行时间："+time());
			loc = location;
		}

		@Override
		public void onProviderDisabled(String provider)
		{
			// Auto-generated method stub
			showLMStatus("provider被用户关闭");
		}

		@Override
		public void onProviderEnabled(String provider)
		{
			// Auto-generated method stub
			showLMStatus("provider被用户开启");
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras)
		{
			// Auto-generated method stub
			if (status == LocationProvider.AVAILABLE)
			{
				showLMStatus("当前GPS状态:可见的");
			}
			else if (status == LocationProvider.OUT_OF_SERVICE)
			{
				showLMStatus("当前GPS状态:服务区外");
			}
			else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE)
			{
				showLMStatus("当前GPS状态:暂停服务");
			}
		}

	};

	/**
	 * 退出app
	 */
	private void exit()
	{
		System.exit(0);
	}
	
	/**
	 * 显示错误信息
	 */
	private void showError(String s)
	{
		tv5.setText(s);
	}
	
	/**
	 * 显示当前连接方式和卫星数量
	 */
	private void showTypeAndNum()
	{
		tv1.setText("当前连接方式：" + currentProvider + "   搜索到：" + satellites
				+ "颗卫星。");
	}
	
	/**
	 * 显示当前经纬度
	 */
	private void showLatlng()
	{

		if (loc != null)
		{
			tv2.setText("当前经度：" + loc.getLongitude() + "\n当前纬度："
					+ loc.getLatitude() + "\n更新时间：" + time());
		}
	}
	/**
	 * 显示当GPS状态
	 */
	private void showGPSStatus(String s)
	{
		tv3.setText(s);
	}
	/**
	 * 显示GPS数据
	 */
	private void showLMStatus(String s)
	{
		tv4.setText(s);
	}

	@SuppressWarnings("deprecation")
	private String time()
	{
		return new Date().toLocaleString();
	}

}
